package com.kantboot.functional.sms.service.service;

import com.kantboot.api.qinucloud.service.IApiQiniuSmsService;
import com.kantboot.functional.common.message.domain.dto.MessageDTO;
import com.kantboot.functional.common.message.enums.MessageStatusCodeEnum;
import com.kantboot.functional.sms.domain.entity.FunctionalSms;
import com.kantboot.functional.sms.repository.FunctionalSmsRepository;
import com.kantboot.functional.sms.service.IFunctionalSmsService;
import com.kantboot.global.exception.GlobalException;
import com.kantboot.util.common.exception.BaseException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class FunctionalSmsServiceImpl implements IFunctionalSmsService {

    @Resource
    private FunctionalSmsRepository repository;

    @Resource
    private IApiQiniuSmsService apiQiniuSmsService;

    @Override
    public void send(MessageDTO messageDTO) {
        FunctionalSms functionalSms = new FunctionalSms();
        // 短信内容
        functionalSms.setContent(messageDTO.getContent());
        // 如果区号为空
        if (messageDTO.getPhoneAreaCode() == null) {
            throw GlobalException.functionalSms.AREA_CODE_IS_NOT_NULL;
        }
        // 接受者号码
        String to = messageDTO.getTo();
        functionalSms.setTo(to);
        // 区号
        functionalSms.setPhoneAreaCode(messageDTO.getPhoneAreaCode());
        // 完整号码
        functionalSms.setFullPhone("+"+messageDTO.getPhoneAreaCode() + to);
        // 消息类型
        functionalSms.setMessageTypeCode(messageDTO.getMessageTypeCode());
        // 初始消息状态
        functionalSms.setMessageStatusCode(MessageStatusCodeEnum.STATUS_CODE_SENDING);
        // 保存消息
        FunctionalSms save = repository.save(functionalSms);
        try {
            // 调用千牛云api发送短信
            apiQiniuSmsService.sendFulltextMessageOne(save.getFullPhone(), messageDTO.getContent());
        } catch (BaseException e) {
            log.error("发送短信失败，失败原因：{}", e.getMessage());
            // 发送失败，更新消息状态
            save.setMessageStatusCode(MessageStatusCodeEnum.STATUS_CODE_FAIL);
            // 设置失败原因编码
            save.setMessageStatusFailReasonCode(e.getStateCode());
            // 设置失败原因
            save.setMessageStatusFailReason(e.getMessage());
            // 保存失败消息
            repository.save(save);
            return;
        }
        // 发送成功，更新消息状态
        save.setMessageStatusCode(MessageStatusCodeEnum.STATUS_CODE_SUCCESS);
        // 保存成功消息
        repository.save(save);

    }

}